import Taro, { Component } from '@tarojs/taro';
import {
  View,
  Text,
  Button,
  Swiper,
  SwiperItem,
  Image,
  WebView,
  RichText,
} from '@tarojs/components';
import './index.scss';
import Banner from '../../static/home/banner.png';
import IconBorder from '../../static/home/line.png';
import { bannerList, bannerRich } from '../../services/program';
import NavigationBar from '../../components/navigationBar/index';
import { fullImgUrl, timeFormat } from '../../utils/utils';
import { getCardInfo, getUserInfo, } from '../../services/user';

import MultiTextModal from '../../components/multi-text-modal/index';
import { activeCard, addCard } from '../../services/card';
import IconScan from '../../static/home/scan.png';
import IconGoods from '../../static/home/goods.png';
import IconDingzhi from '../../static/home/dingzhi.png';
import IconUser from '../../static/home/user.png';
import bg from '../../static/home/bg.png';

export default class Index extends Component {
  config = {
    navigationBarTitleText: '中鹿岛',
  };

  state = {
    userInfo: Taro.getStorageSync('userInfo') || null,
    list: [],
    isShowWebView: false,
    webViewUrl: '',
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    isShowModal: false,
    contentArr: null,
    cardInfo: null,
    modalTitle: '',
    comfirmText: '',
    cancleText: '',
    tabsList: [
      { icon: IconScan, text: '首页', type: 'scan' },
      { icon: IconGoods, text: '商场', type: 'shop' },
      { icon: IconScan, text: '扫码提货', type: 'scan' },
      { icon: IconDingzhi, text: '定制', type: 'custom' },
      { icon: IconUser, text: '我的', type: 'user' },
    ],
    rich: '',
  };

  componentWillMount() {
    this.scan();
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() {
  }
  componentDidShow() {
    this.setState(
      {
        userInfo: Taro.getStorageSync('userInfo') || null,
      },
      () => {
        if (this.state.userInfo) {
          getUserInfo({
            id: this.state.userInfo.id + '',
          }).then(res => {
            Taro.setStorageSync('userInfo', res);
            this.setState({
              userInfo: res,
            });
          });
        }
      }
    );
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  getBannerList() {
    bannerList().then(res => {
      console.log(res)
      res.forEach(element => {
        element.cover = fullImgUrl(element.cover);
      });
      this.setState({
        list: res,
      });
    });
    bannerRich().then(res => {
      res = res.replace(/\<img/gi, '<img style="width: 100% !important; class="rich-img"');
      this.setState({
        rich: res,
      });
    });
  }

  onShareAppMessage() {
    let setting = Taro.getStorageSync('setting');
    return {
      title: `${setting.share_title}`,
      path: '/pages/home/index',
      imageUrl: `${fullImgUrl(setting.share_img)}`,
    };
  }

  scan = () => {

    // Taro.setStorageSync('card_no', '00200820000017192')
    // Taro.navigateTo({
    //   url: `/subPackageWork/pages/exchange/index?type=coupon`
    // })
    // return
    if (!this.state.userInfo) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/login/index',
      });
    } else {
      let self = this;
      Taro.scanCode({
        onlyFromCamera: true,
        success(res) {
          if (res.result.slice(0, 2) === '00') {
            Taro.setStorageSync('card_no', res.result);
            Taro.navigateTo({
              url: `/subPackageWork/pages/exchange/index?type=coupon`,
            });
          } else {
            getCardInfo({
              card_no: res.result,
            }).then(data => {
              if (data.status === 6) {
                Taro.setStorageSync('card_no', data.card_no);
                if (data.user) {
                  Taro.setStorageSync('barcode_address', data.user.level_customize_pic);
                }else{
                  Taro.setStorageSync('barcode_address', '');
                }
                Taro.setStorageSync('attr_name', data.attr_name);
                Taro.navigateTo({
                  url: `/subPackageWork/pages/exchange/index`,
                });
              } else if (data.status === 4) {
                addCard({
                  card_no: data.card_no,
                }).then(
                  res => {
                    Taro.showToast({
                      title: '添加成功',
                      icon: 'none',
                    });
                    // 二级代理从一级代理领卡
                    let contentArr = [
                      {
                        key: '卡号',
                        value: data.card_no,
                      },
                      {
                        key: '类型',
                        value: data.attr_name,
                      },
                    ];
                    self.setState({
                      contentArr: contentArr,
                      isShowModal: true,
                      cardInfo: data,
                      modalTitle: '已加入我的兑换卡',
                      comfirmText: '继续添加',
                      cancleText: '关闭',
                    });
                  },
                  () => {
                    this.setState({
                      isShowModal: false,
                    });
                  }
                );
              } else if (data.status === 5) {
                let contentArr = [
                  {
                    key: '卡号',
                    value: data.card_no,
                  },
                  {
                    key: '类型',
                    value: data.attr_name,
                  },
                ];
                self.setState({
                  contentArr: contentArr,
                  isShowModal: true,
                  cardInfo: data,
                  modalTitle: '兑换卡',
                  comfirmText: '去付款',
                  cancleText: '取消',
                });
              } else {
                // Taro.showToast({
                //   title: '卡的状态不对',
                //   icon: 'none'
                // })
              }
            });
          }
        },
      });
    }
  };

  shopping = () => {
    Taro.navigateTo({
      url: '/subPackageWork/pages/goods-list/index',
    });
  };

  customized = () => {
    Taro.navigateTo({
      url: `/subPackageWork/pages/customized/index?id=1&showBtn=1`,
    });
  };

  goUser = () => {
    Taro.navigateTo({
      url: '/pages/user/index',
    });
  };

  bannerClickHandler(banner) {
    if (banner.type === 1) {
      // 链接
      // this.setState({
      //   isShowWebView: true,
      //   webViewUrl: banner.url
      // })
      Taro.navigateTo({
        // url: `/subPackageWork/pages/web-view/index?url=${banner.url}`
        url: `/subPackageWork/pages/webView/index?url=${banner.url}`,
      });
    } else if (banner.type === 2) {
      // 商品详情
      Taro.navigateTo({
        url: `/pages/goods-detail/index?id=${banner.goods_id}`,
      });
    } else if (banner.type === 3) {
      // 定制
      Taro.navigateTo({
        url: `/subPackageWork/pages/customized/index?id=${banner.article_id}`,
      });
    }
  }

  outStorage() {
    console.log('out');
    Taro.navigateTo({
      url: `/subPackageWork/pages/choose-agency/index`,
    });
  }

  enterStorage() {
    Taro.navigateTo({
      url: `/subPackageWork/pages/storage-success/index?type=0`,
    });
  }

  cancleCb() {
    this.setState({
      isShowModal: false,
    });
  }

  confirmCb() {
    if (this.state.cardInfo.status === 4 && this.state.userInfo.level !== 0) {
      this.setState(
        {
          isShowModal: false,
        },
        () => {
          this.scan();
        }
      );
    } else if (this.state.cardInfo.status === 5) {
      activeCard({
        card_no: this.state.cardInfo.card_no,
        pay_type: 3,
        pay_platform: 1,
      }).then(data => {
        Taro.requestPayment({
          ...JSON.parse(data.payload).metadata,
        }).then(
          data => {
            this.setState(
              {
                isShowModal: false,
              },
              () => {
                Taro.navigateTo({
                  url: `/subPackageWork/pages/apply-success/index`,
                });
              }
            );
          },
          data => {
            this.setState(
              {
                isShowModal: false,
              },
              () => {
                Taro.navigateTo({
                  url: `/pages/my-order/index`,
                });
              }
            );
          }
        );
      });
    }
  }

  tabItemClickCb(item) {
    switch (item.type) {
      case 'scan':
        this.scan();
        break;
      case 'shop':
        this.shopping();
        break;
      case 'custom':
        this.customized();
        break;
      case 'user':
        this.goUser();
        break;
      default:
        break;
    }
  }

  render() {
    const {
      tabsList,
      isShowModal,
      contentArr,
      modalTitle,
      userInfo,
      comfirmText,
      list,
      isShowWebView,
      webViewUrl,
      navigationBarHeight,
      rich,
    } = this.state;
    return (
      <View className='home'>
      </View>
    );
  }
}
